package cn.chencq.thread;

public class TraditionalThreadCommunication {

	public static void main(String[] args) {
		new TraditionalThreadCommunication().test2();
	}

	public void test1() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					synchronized (TraditionalThreadCommunication.class) {
						for (int j = 1; j <= 10; j++) {
							System.out.println("sub thread sequece of " + j + ", loop of " + i);
						}
					}
				}
			}
		}).start();

		for (int i = 1; i <= 50; i++) {
			synchronized (TraditionalThreadCommunication.class) {
				for (int j = 1; j <= 100; j++) {
					System.out.println("main thread sequece of " + j + ", loop of " + i);
				}
			}
		}
	}

	public void test2() {
		final Business bussiness = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					bussiness.sub(i);
				}
			}
		}).start();

		for (int i = 1; i <= 50; i++) {
			bussiness.main(i);
		}
	}

	class Business {
		private boolean bShouldSub = true;

		public synchronized void main(int i) {
			while (!bShouldSub) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int j = 1; j <= 10; j++) {
				System.out.println("main thread sequece of " + j + ", loop of " + i);
			}
			bShouldSub = false;
			this.notify();
		}

		public synchronized void sub(int i) {
			while (bShouldSub) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int j = 1; j <= 100; j++) {
				System.out.println("sub thread sequece of " + j + ", loop of " + i);
			}
			bShouldSub = true;
			this.notify();
		}
	}

}
